import { GLFolderContainer } from "../../app/GLFolderContainer";
import { GLFolderLike } from "../../app/GLFolderLike";
import { GLFolder } from '../../app/GLFolder';
import { Component } from '@angular/core';
import { Http } from '@angular/http';
import { NavController, NavParams, PopoverController, LoadingController } from 'ionic-angular';
import { GLBookChapter } from '../../app/GLBookChapter';
import { ChapterPage } from '../chapter/chapter';
import { ParentListPage } from '../../app/parentList.component';
import { GLItem } from '../../app/GLItem';
import { GLAPI } from '../../app/GLAPI.service';

/*
  Generated class for the List page.

  See http://ionicframework.com/docs/v2/components/#navigation for more info on
  Ionic pages and navigation.
*/
@Component({
  selector: 'page-list',
  templateUrl: 'list.html'
})
export class ListPage {

  private item: GLFolderLike;
  private catalog: GLFolder;
  private content: GLItem[];

  constructor(private navCtrl: NavController, navParams: NavParams, http: Http, private popoverCtl: PopoverController, loadingCtl: LoadingController, glAPI: GLAPI) {
    window["LIST_PAGE"] = this;
    console.log(navParams.data);
    let loading = loadingCtl.create();
    loading.present();
    glAPI.getCatalog().then((catalog: GLFolder) => {
      this.catalog = catalog;
      if (navParams.data.folderID) {
        return (<GLFolderContainer><any>catalog.getChildByID(navParams.data.folderID)).asFolder();
      }
      else {
        return catalog;
      }
    }).then((item) => {
      this.item = item;
      this.content = this.item.getContent();
      loading.dismiss();
    }).catch((err) => {
      console.error(err);
      loading.dismiss();
    });
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad ListPage');
  }

  open(folder) {
    ListPage.open(folder, this.navCtrl);
  }

  static open(folder, navCtrl: NavController, verse?: string) {
    if (folder instanceof GLBookChapter) {
      navCtrl.push(ChapterPage, { itemID: folder.id, verse: verse });
    }
    else {
      navCtrl.push(ListPage, { folderID: folder.id });
    }
  }

  openParentList(event) {
    this.popoverCtl.create(ParentListPage, { item: this.item }).present({
      ev: event
    });
  }

}
